package org.example.view.page;

import org.example.controller.UserController;
import org.example.data.Result;
import org.example.data.User;

import javax.swing.*;
import java.awt.*;

public class UpdatePassword extends JFrame {
    private JButton update;
    private JPasswordField[] passwordField;
    private String[] labels = {"请输入原密码", "请输入修改后密码", "请再次输入密码"};

    public UpdatePassword(User user) {
        super("修改密码");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 创建和设置主面板，使用GridBagLayout布局
        JPanel mainPanel = new JPanel(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        passwordField = new JPasswordField[3];

        // 添加label和passwordField到主面板
        for (int i = 0; i < labels.length; i++) {
            JLabel label = new JLabel(labels[i]);
            passwordField[i] = new JPasswordField(20);

            gbc.gridx = 0;
            gbc.gridy = i;
            mainPanel.add(label, gbc);

            gbc.gridx = 1;
            mainPanel.add(passwordField[i], gbc);
        }

        // 添加修改密码按钮
        update = new JButton("修改密码");
        gbc.gridx = 0;
        gbc.gridy = labels.length;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        mainPanel.add(update, gbc);
        update.addActionListener(e->{
            String[] password = new String[3];
            for (int i = 0; i < 3; i++) {
                password[i] = passwordField[i].getText();
            }
            if (password[1].equals(password[2])){
                // 进行修改密码处理
                Result<Integer> userResult = new UserController().update(user.getId(), password[0],password[1]);

                if (userResult.getStatus()) {
                    // 修改成功，弹出成功信息并关闭页面
                    JOptionPane.showMessageDialog(UpdatePassword.this, "修改成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                    dispose(); // 关闭当前登录界面
                } else {
                    // 登录失败，弹出错误信息
                    JOptionPane.showMessageDialog(UpdatePassword.this, userResult.getMessage(), "修改失败", JOptionPane.ERROR_MESSAGE);
                }
            }else {
                JOptionPane.showMessageDialog(UpdatePassword.this, "两次输入密码不同","修改失败", JOptionPane.ERROR_MESSAGE);
            }


        });

        add(mainPanel);

        setSize(400, 200);
        setLocationRelativeTo(null);
        setVisible(true);

    }
}
